#pragma once

#include <iostream>
#include <functional>
#include <unordered_map>
#include "Log.hpp"
#include "Sock.hpp"
#include "Epoller.hpp"
#include "Util.hpp"
#include <cassert>
#include "Protocol.hpp"

namespace tcpserver
{

    class Connection;
    class TcpServer;

    static const uint16_t defaultport = 8080;
    static const int num = 64;

    using func_t = std::function<void(Connection *)>;
    // using handler_t = std::function<void(const std::string &package)>;

    class Connection
    {
    public:
        Connection(int sock, TcpServer *tsp) : sock_(sock), tsp_(tsp)
        {
        }
        void Register(func_t r, func_t s, func_t e)
        {
            recver_ = r;
            sender_ = s;
            excepter_ = e;
        }
        ~Connection()
        {
        }
        void Close()
        {
            close(sock_);
        }

    public:
        int sock_;
        std::string inbuffer_;  // 输入缓冲区
        std::string outbuffer_; // 输出缓冲区

        func_t recver_;   // 处理读
        func_t sender_;   // 处理写
        func_t excepter_; // 处理异常

        TcpServer *tsp_; // 回指针 // ??

        uint64_t lasttime_;
    };

    class TcpServer
    {
    public:
        TcpServer(func_t func, uint16_t port = defaultport)
            : service_(func), port_(port), num_(0), revs_(nullptr)
        {
        }

    public:
        void initServer()
        {
            // 1. socket
            sock_.Socket();
            sock_.Bind(port_);
            sock_.Listen();
            logMessage(NORMAL, "listensock_ : %d", sock_.Fd());
            // 2. Epoll
            epoller_.Create();
            // 3. add sock to epoller, need set non_block before
            AddConnection(sock_.Fd(), EPOLLIN | EPOLLET,
                          std::bind(&TcpServer::Accepter, this, std::placeholders::_1), nullptr, nullptr);

            revs_ = new struct epoll_event[num];
            num_ = num;
        }
        void EnableReadWrite(Connection *conn, bool readable, bool wirteable)
        {
            uint32_t event = (readable ? EPOLLIN : 0) | (wirteable ? EPOLLOUT : 0) | EPOLLET;
            epoller_.Control(conn->sock_, event, EPOLL_CTL_ADD);
        }
        void Dispatcher()
        {
            int timeout = 1000;
            while (true)
            {
                Loop(timeout);
                // logMessage(DEBUG, "time out....");

                // 计算lasttime离上次更新过了多久, 超过期限直接关掉
                // TODO
            }
        }
        ~TcpServer()
        {
            sock_.Close();
            epoller_.Close();
            if (nullptr == revs_)
                delete[] revs_;
        }

    private:
        void Recver(Connection *conn)
        {
conn->lasttime_ = time(nullptr);

            char buffer[1024];
            while (true)
            {
                ssize_t s = recv(conn->sock_, buffer, sizeof(buffer) - 1, 0);
                if (s > 0)
                {
                    buffer[s] = 0;
                    conn->inbuffer_ += buffer;

                    logMessage(DEBUG, "\n%s", conn->inbuffer_);
                    service_(conn); // 回调
                }
                else if (s == 0)
                {
                    if (conn->excepter_)
                    {
                        conn->excepter_(conn);
                        return;
                    }
                }
                else
                {
                    if (errno == EAGAIN || errno == EWOULDBLOCK)
                        break;
                    else if (errno == EINTR)
                        continue;
                    else
                    {
                        if (conn->excepter_)
                        {
                            conn->excepter_(conn);
                            return;
                        }
                    }
                }
            }
        }
        void Sender(Connection *conn)
        {
            conn->lasttime_ = time(nullptr);

            bool ok = true;
            while (true)
            {
                ssize_t s = send(conn->sock_, conn->outbuffer_.c_str(), conn->outbuffer_.size(), 0);
                if (s > 0)
                {
                    if (conn->outbuffer_.empty())
                    {
                        EnableReadWrite(conn, true, false);
                        break;
                    }
                    else
                        conn->outbuffer_.erase(0, s);
                }
                else
                {
                    if (errno == EAGAIN || errno == EWOULDBLOCK)
                        break;
                    else if (errno == EINTR)
                        continue;
                    else
                    {
                        if (conn->excepter_)
                        {
                            conn->excepter_(conn);
                            return;
                        }
                    }
                }
            }

            if (conn->outbuffer_.empty())
                conn->tsp_->EnableReadWrite(conn, true, true);
            else
                conn->tsp_->EnableReadWrite(conn, true, false);
        }
        void Excepter(Connection *conn)
        {
            logMessage(DEBUG, "Excepter begin");
            epoller_.Control(conn->sock_, 0, EPOLL_CTL_MOD);
            conn->Close();
            connections_.erase(conn->sock_);

            logMessage(DEBUG, "close all resourse of %d fd", conn->sock_);

            delete conn;
        }

        void Accepter(Connection *conn)
        {
            for (;;)
            {
                std::string clientip;
                uint16_t clientport;
                int err = 0;
                int sock = sock_.Accept(&clientip, &clientport, &err);
                if (sock > 0)
                {
                    AddConnection(
                        sock, EPOLLIN | EPOLLET,
                        std::bind(&TcpServer::Recver, this, std::placeholders::_1),
                        std::bind(&TcpServer::Sender, this, std::placeholders::_1),
                        std::bind(&TcpServer::Excepter, this, std::placeholders::_1));

                    logMessage(DEBUG, "get a new link, info: [%s:%d]", clientip.c_str(), clientport);
                }
                else
                {
                    if (err == EAGAIN || err == EWOULDBLOCK)
                        break;
                    else if (err == EINTR)
                        continue;
                    else
                        break;
                }
            }
        }
        void AddConnection(int sock, uint32_t events, func_t recver, func_t sender, func_t excepter)
        {
            // 1. new and init Connections, add into connections
            if (events & EPOLLET)
                Util::setNonBlock(sock);
            Connection *conn = new Connection(sock, this);
            // 2. register callback function for the sock
            conn->Register(recver, sender, excepter);

            // 2. add sock and its events enroll epoll
            bool r = epoller_.AddEvent(sock, events);
            assert(r);
            (void)r;

            // 3. add kv into connections
            connections_.insert(std::make_pair(sock, conn));

            logMessage(DEBUG, "add new sock : %d: inepoll and unordered_map", sock);
        }
        bool IsConnectionExists(int sock)
        {
            auto iter = connections_.find(sock);
            return iter != connections_.end();
        }
        void Loop(int timeout)
        {
            int n = epoller_.Wait(revs_, num_, timeout);
            for (int i = 0; i < n; ++i)
            {
                int sock = revs_->data.fd;
                uint32_t events = revs_[i].events;

                if (events & EPOLLERR)
                    events |= (EPOLLIN | EPOLLOUT);
                if (events & EPOLLHUP)
                    events |= (EPOLLIN | EPOLLOUT);

                // 各用各的回调函数
                if (IsConnectionExists(sock) && (events & EPOLLIN))
                    if (connections_[sock]->recver_)
                        connections_[sock]->recver_(connections_[sock]);
                if (IsConnectionExists(sock) && (events & EPOLLOUT))
                    if (connections_[sock]->sender_)
                        connections_[sock]->sender_(connections_[sock]);
                // ?
            }
        }

    private:
        uint16_t port_;
        Sock sock_;
        Epoller epoller_;
        std::unordered_map<int, Connection *> connections_;
        struct epoll_event *revs_;
        int num_;
        func_t service_;
    };
}